package com.example.weatherreport.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Base64;

import com.google.gson.Gson;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

//SharedPreferences存取图片
public class SpUtils {

    private static final String DEFAULT_SP_NAME = "default_sp";

    public static void saveDrawable(Context context, Bitmap bitmap, String key) {
        SharedPreferences sharedPreferences=context.getSharedPreferences(DEFAULT_SP_NAME,context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 50, baos);
        String imageBase64 = new String(Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT));
        editor.putString(key,imageBase64 );
        editor.commit();
    }

    public static Drawable getDrawableByKey(Context context, String key) {
        SharedPreferences sharedPreferences=context.getSharedPreferences(DEFAULT_SP_NAME,context.MODE_PRIVATE);
        String temp = sharedPreferences.getString(key, "");
        ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(temp.getBytes(), Base64.DEFAULT));
        return Drawable.createFromStream(bais, "");
    }
}